/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.common;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


/**
 * This class defines a simple time interval. It has start date, end date and a step to retrieve values at. 
 *
 * @author Basil Shikin
 *
 */
public class TimeInterval
{
    private final Date startDate;
    private final Date endDate;
    private final TimeStep timeStep;
    
    
    /**
     * Create new interval that ends now.
     * 
     * @param startDate Interval start. Must not be null.
     * @param timeStep  Interval step. Must not be null.
     */
    public TimeInterval(Date startDate, TimeStep timeStep)
    {
        this( startDate, new Date(), timeStep );
    }
    
    /**
     * Create new interval.
     * 
     * @param startDate Interval start. Must not be null.
     * @param endDate   Interval end. Must not be null.
     * @param timeStep  Interval step. Must not be null.
     */
    public TimeInterval(Date startDate, Date endDate, TimeStep timeStep)
    {
        if ( startDate == null ) throw new IllegalArgumentException("Invalid start date specified");
        if ( endDate == null ) throw new IllegalArgumentException("Invalid end date specified");
        if ( timeStep == null ) throw new IllegalArgumentException("Invalid time step specified");
        
        this.startDate = startDate;
        this.endDate = endDate;
        this.timeStep = timeStep;
    }
    
    public Date getStartDate()
    {
        return startDate;
    }

    public Date getEndDate()
    {
        return endDate;
    }

    public TimeStep getTimeStep()
    {
        return timeStep;
    }

    /**
     * Count interval steps. This is number of times time step fits into the interval.
     * 
     * @return Number of steps in this interval
     */
    public int countSteps()
    {
        int count = 1;
        
        Date fromDate = startDate;
        Date toDate   = retrieveNextDate( fromDate );
        
        while ( toDate != null )
        {
            fromDate = toDate;
            toDate   = retrieveNextDate( toDate );
            
            count += 1;
        }
        return count;
    }
    
    /**
     * Retrieve next date for this interval. If interval step is a date and provided
     * date is 9th of May, 10th of May will be returned. If end of interval is 9th of May,
     * null will be returned.
     * 
     * @param currentDate Date to return e
     * 
     * @return Next date in the interval or null if none (i.e. date is out of interval range).
     */
    public Date retrieveNextDate( Date currentDate )
    {
        if ( currentDate.equals( endDate ) ) return null;
        
        final Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime( currentDate );
        
        if ( timeStep == TimeStep.DAY )
        {
            calendar.add( Calendar.DAY_OF_MONTH, 1 );
        }
        else if ( timeStep == TimeStep.MONTH )
        {
            calendar.add( Calendar.MONTH, 1 );
        }
        else if ( timeStep == TimeStep.WEEK )
        {
            calendar.add( Calendar.WEEK_OF_MONTH, 1 );
        }
        else
        {
            throw new IllegalArgumentException("Unsupported time step: " + timeStep );
        }
        
        final Date nextDate = calendar.getTime();
        return nextDate.getTime() <= endDate.getTime() ? nextDate : null;
    }
    
    /**
     * Retrieve previous date for this interval. If interval step is a date and provided
     * date is 9th of May, 8th of May will be returned. If start of interval is 9th of May,
     * null will be returned.
     * 
     * @param currentDate Date to return e
     * 
     * @return Previous date in the interval or null if none (i.e. date is out of interval range).
     */
    public Date retrievePreviousDate( Date currentDate )
    {
        if ( currentDate.equals( startDate ) ) return null;
        
        final Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime( currentDate );
        
        if ( timeStep == TimeStep.DAY )
        {
            calendar.add( Calendar.DAY_OF_MONTH, -1 );
        }
        else if ( timeStep == TimeStep.MONTH )
        {
            calendar.add( Calendar.MONTH, -1 );
        }
        else if ( timeStep == TimeStep.WEEK )
        {
            calendar.add( Calendar.WEEK_OF_MONTH, -1 );
        }
        else
        {
            throw new IllegalArgumentException("Unsupported time step: " + timeStep );
        }
        
        final Date previousDate = calendar.getTime();
        return previousDate.getTime() >= startDate.getTime() ? previousDate : null;
    }

    @Override
    public String toString()
    {
        return "[Time interval: from: " + startDate + ", to:" + endDate + ", step: " + timeStep + "]";
    }
}
